package com.yuxi.al.bracketsMatch;

import com.google.common.collect.Lists;

import java.util.List;
import java.util.Stack;

/**
 * 使用栈来实现带括号的四则元素
 * Created by yuxi on 2017/8/29.
 */
public class BracketsMatch {
    public static void main(String[] args) {
        List<String> list = Lists.newArrayList();
        list.add("(");
        list.add("1");
        list.add("+");
        list.add("(");
        list.add("(");
        list.add("2");
        list.add("+");
        list.add("3");
        list.add(")");
        list.add("*");
        list.add("(");
        list.add("4");
        list.add("*");
        list.add("5");
        list.add(")");
        list.add(")");
        list.add(")");

        System.out.println(list);

        Double res = bracketOperator(list);
        System.out.println(res);
    }

    private static Double bracketOperator(List<String> list) {
        Stack<String> op = new Stack<String>();
        Stack<Double> num = new Stack<Double>();
        if (list.isEmpty()) {
            return 0.0;
        }
        for (String o : list) {
            if (o.equals("(")) continue;
            if (o.equals(",")) continue;
            else if (o.equals("+")) op.push(o);
            else if (o.equals("-")) op.push(o);
            else if (o.equals("*")) op.push(o);
            else if (o.equals("/")) op.push(o);
            else if (o.equals(")")) {
                String ops = op.pop();
                Double d = num.pop();
                // 需要注意顺序
                if (ops.equals("+")) d =  num.pop()+d;
                else if (ops.equals("-")) d = num.pop()-d;
                else if (ops.equals("*")) d =  num.pop()*d;
                else if (ops.equals("/")) d = num.pop()/d;
                num.push(d);
            } else {
                num.push(Double.valueOf(o));
            }

        }
        return num.pop();
    }
}
